package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: wf
 * @Desc:  分类管理
 * @Date: 2022-08-22 18:36:24
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void delete(Long id) {

        // 先判断当前分类下是否有关联的菜品或套餐
        // 判断菜品
        LambdaQueryWrapper<Dish> dishLqw = new LambdaQueryWrapper<>();
        dishLqw.eq(Dish::getCategoryId, id);
//        List<Dish> dishList = dishService.list(dishLqw);
        int dishCount = dishService.count(dishLqw);
        if (dishCount > 0) {
            //有关联的菜品，提示不能删除，抛出一个业务异常
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }

        // 判断套餐
        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<>();
        setmealLqw.eq(Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealLqw);
        if (setmealCount > 0) {
            // 有关联套餐，提示不能删除，抛出一个业务异常
            throw new CustomException("有关联的套餐，不能被删除");
        }

        // 没有任何关联，直接删除
        this.removeById(id);
    }
}
